<template>
  <div>
    <input type="file" @change="fileChange" />
    <el-button @click="handleClick">点我</el-button>
    <slot name="full" :data="fullData"></slot>
  </div>
</template>
<script>
import sparkMd5 from "spark-md5";
export default {
  name: "fileUpload",
  data() {
    return {
      fullData: "我是子组件的data",
    };
  },
  methods: {
    async fileChange(e) {
      console.log(e,"--------------------")
      if (!e.target.files[0]) return;
      let chunks = this.createChunks(e.target.files[0]);
      let hash = await this.getHash(chunks);
      console.log(e.target.files[0], chunks, hash);
    },
    createChunks(file, size = 1024 * 1024) {
      let result = [];
      for (let i = 0; i < file.size; i += size) {
        result.push(file.slice(i, i + size));
      }
      return result;
    },
    getHash(chunks) {
      return new Promise((resolve) => {
        const spark = new sparkMd5();
        function _read(i) {
          if (i >= chunks.length) {
            resolve(spark.end());
            return;
          }
          const blod = chunks[i];
          const reader = new FileReader();
          reader.onload = function (e) {
            spark.append(e.target.result);
            _read(i + 1);
          };
          reader.readAsArrayBuffer(blod);
        }
        _read(0);
      });
    },
    handleClick() {
      this.$emit("fileButtonClick");
      console.log("我是子组件的点击事件我被触发了吗");
    },
  },
};
</script>
<style scoped></style>
